<template>
    <van-row>
        <van-col span="2">
            <van-nav-bar left-arrow @click-left="onClickLeft" :border="false" style="width: 10px;" />

        </van-col>
        <van-col span="2">
            <van-icon name="wap-home-o" size="25px" style="line-height: 44px; padding-left: 5px;" @click="onHome" />
        </van-col>
        <van-col span="16" style="text-align: center; line-height: 44px; ">搜索</van-col>
        <van-col span="2"><van-icon name="search" size="25px" style="line-height: 44px; " /></van-col>
        <van-col span="2"><van-icon name="bars" size="25px" style="line-height: 44px; " /></van-col>
    </van-row>
    <van-search v-model="keyword" placeholder="请输入搜索关键词" wrap-with-form show-action @search="onSearch"
        @cancel="onCancel" @input="handelInput"/>

    <!--搜索拿到的数据展示     v-if="keyword.trim()" 如果当前输入去除空格之后还是为空 那么就不显示下面的数据-->
    <div class="container" v-if="keyword.trim()">
        <span style="border-bottom: 3px solid yellow; margin-left: 10px;">新车</span>
        <van-swipe-cell style="margin-top: 10px;" v-for="(item, index) in productCardata" :key="index">
            <van-row>
                <van-col span="7">
                    <van-image width="100%" height="80"
                        :src="item.carimg" />
                </van-col>
                <van-col span="17">
                    <div style="padding-left: 5px; padding-bottom: 5px;margin-top: 10px;">{{item.carname}}</div>
                    <div style="padding-left: 5px; color: red;">{{ item.minprice }} - {{item.maxprice}}万</div>
                </van-col>

            </van-row>
            <hr>
            </hr>
            <!--如果没有匹配结果显示的话 -->
            <div v-if="productCardata.length == 0" style="text-align: center;">
                没有找到搜索匹配的结果
            </div>
        </van-swipe-cell>
    </div>
    <!--搜索记录存储区域-->
<div class="history-container" v-if="searchHistoy.length">
<div class="history-header">
    <span style="border-bottom: 3px solid yellow; margin-left: 10px;">搜索历史</span>
    <div class="history-content">
        <!--展示数据-->
        <van-tag class="tags" v-for="(item,index) in searchHistoy" :key="index" closeable size="large"  @close="deleteHistory(index)">
        {{item}}
        </van-tag>
    </div>
    <van-button size="small" text @click="clearAllHistory">清除全部历史记录</van-button>
</div>

</div>

    <!--推荐的商品信息-->
    <div class="productClass" v-if="!keyword.trim()">
        <span style="border-bottom: 3px solid yellow; margin-left: 10px;">推荐</span>
         <van-swipe-cell style="margin-top: 10px;" v-for="(item, index) in carData" :key="index">
            <van-row>
                <van-col span="7">
                    <van-image width="100%" height="80"
                        :src="item.carimg" />
                </van-col>
                <van-col span="17">
                    <div style="padding-left: 5px; padding-bottom: 5px;margin-top: 10px;">{{item.carname}}</div>
                    <div style="padding-left: 5px; color: red;">{{ item.minprice }} - {{item.maxprice}}万</div>
                    <van-button type="warning" size="small" @click="onzx">去咨询</van-button>&nbsp;
                    <van-button type="danger" size="small" @click="ongm">立即购买</van-button>
                </van-col>

            </van-row>
            <!-- <van-action-bar>
                        <van-action-bar-button type="warning" text="加入购物车" />
                        <van-action-bar-button type="danger" text="立即购买" />
                </van-action-bar> -->
        </van-swipe-cell>
    </div>

</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { CarGoodsApi } from '../api'

import { useRouter } from 'vue-router'
const router = useRouter()

const onHome = () => router.push('/')

const keyword = ref('');

//定义搜索存储变量 记录
const searchHistoy= ref([])

//保存历史纪律
const saveHistory = (keyword) => {
// 如果有重复的数据，直接删除掉 添加新的数据
const index = searchHistoy.value.indexOf(keyword)
if (index !== -1) searchHistoy.value.splice(index, 1)

//每次新的搜索数据 是不是要放在最前面
searchHistoy.value.unshift(keyword)
//限制最多显示10条数据
if(searchHistoy.value.length > 10) {
    //删除最后一个元素 就是最新的数据 因为我们每次都是放在最前面 所以最新的数据在最下面
    searchHistoy.value.pop()
    }

// 持久化存储历史记录
//  localStorage.setItem('searchHistoy', JSON.stringify(searchHistoy.value))
 window.localStorage.setItem('searchHistoy', JSON.stringify(searchHistoy.value))

}
//处理搜索输入

const handelInput =()=>{
     const currentKeyword = keyword.value.trim()
     if(currentKeyword === ''){
        //如果没有输入 直接返回空数组
        productCardata.value = []
     }
}


const onSearch = (val) => {
    console.log(val);
    const currentKeyword = val.trim()
    //判断不为空就保存
    if(currentKeyword) {
        saveHistory(currentKeyword)
    }

}

//删除历史记录某一个数据
const deleteHistory = (index)=>{
    searchHistoy.value.splice(index,1)
    localStorage.setItem('searchHistoy', JSON.stringify(searchHistoy.value))
}
//删除全部数据
const clearAllHistory = ()=>{
    searchHistoy.value = []
    localStorage.removeItem('searchHistoy')
}

const onCancel = () => {
    console.log("取消");
    keyword.value = ''
};
//定义汽车的数据
const productCardata = ref([])

//监听事件 为了实时更新搜索的结果
watch(keyword, (newVal) => {
    //去空格之后在去做执行搜索逻辑
    const keyword = newVal.trim()
    if (keyword) {
        //调用本地数据 或后台传递过来的数据
        mockSearch(keyword)
    } else {
        //如果没有输入 直接返回空数组
        productCardata.value = []
    }
})

onMounted(()=>{
    CallCargoods()
})

//模拟数据 这个地方后期需要调用后台api接口
const mockSearch = (keyword) => {

    // const mockData = [
    //     { id: 101, name: '北京奔驰-奔驰E级', minprice: '28.89', maxprice: '38.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/9b08b1c3602645d7ad7574aeb71b6ce3~480x0.jpg' },
    //     { id: 102, name: '北京奔驰-奔驰C级', minprice: '21.89', maxprice: '26.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/e8abf034d5504085a9850c7b7632b065~480x0.jpg' },
    //     { id: 103, name: '北京奔驰-奔驰S级', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/8c904b55208540b3bb0caad827b8226f~480x0.jpg' },
    //     { id: 104, name: '路虎(进口)-揽胜', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/08ce9dde46f64638aa4df622ce69b497~480x0.jpg' },
    //     { id: 105, name: '华晨宝马-宝马5系', minprice: '32.89', maxprice: '40.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/3964028127a0462c97d2611cd8e1a0a1~480x0.jpg' },

    // ]
    // //模拟搜索逻辑
    // setTimeout(() => {
    //     // 从搜索中获取关键字，并进行数据筛选
    //     productCardata.value = mockData.filter(item => item.name.includes(keyword))
    // },300)
    CarGoodsApi.select.call({carname:keyword}).then(res=>{
        console.log(res);
        // 解决大小写问题
        productCardata.value = res.filter(item=>item.carname.toLowerCase().includes(keyword.toLowerCase()))
        
    })

}

const carData =ref([
      { id: 101, name: '北京奔驰-奔驰E级', minprice: '28.89', maxprice: '38.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/9b08b1c3602645d7ad7574aeb71b6ce3~480x0.jpg' },
        { id: 102, name: '北京奔驰-奔驰C级', minprice: '21.89', maxprice: '26.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/e8abf034d5504085a9850c7b7632b065~480x0.jpg' },
        { id: 103, name: '北京奔驰-奔驰S级', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/8c904b55208540b3bb0caad827b8226f~480x0.jpg' },
        { id: 104, name: '路虎(进口)-揽胜', minprice: '128.89', maxprice: '138.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/08ce9dde46f64638aa4df622ce69b497~480x0.jpg' },
        { id: 105, name: '华晨宝马-宝马5系', minprice: '32.89', maxprice: '40.98', img: 'https://p3-dcd.byteimg.com/img/tos-cn-i-dcdx/3964028127a0462c97d2611cd8e1a0a1~480x0.jpg' },

])

const CallCargoods=()=>{
    CarGoodsApi.select.call().then(res=>{
        console.log(res);
        carData.value = res
    })
}

const onzx = ()=>{
    alert("咨询成功")
}
const ongm = ()=>{
    alert("购买成功")
}
 //返回上一级
 const onClickLeft = () => history.back();
</script>

<style scoped>
.van-search {
    width: 100%;
    background-color: #fff;
}

.history-header {
    margin-top: 10px;
}

.history-content {
    margin-top: 10px;
    margin-bottom: 10px;
}

.tags {
    margin-left: 5px;
}

:deep(.van-nav-bar .van-icon) {
    font-size: 20px;
    color: #121213;
}

:deep(.van-nav-bar__left) {
    width: 10px;
}
.history-header{
    margin-top: 10px;
}
.history-content{
    margin-top: 10px;
    margin-bottom: 10px;
}
.tags{
    margin-left: 5px;
}
.van-button{
    border-radius: 20px;
}
.van-button--small{
    height: 25px;
}
</style>